package com.tianqicode.spring.context.support;

import com.tianqicode.spring.beans.BeansException;
import com.tianqicode.spring.beans.factory.config.BeanPostProcessor;
import com.tianqicode.spring.context.ApplicationContext;
import com.tianqicode.spring.context.ApplicationContextAware;
import com.tianqicode.spring.context.ApplicationEventPublisher;
import com.tianqicode.spring.context.ApplicationEventPublisherAware;

public class ApplicationContextAwareProcessor implements BeanPostProcessor {

    private final ApplicationContext applicationContext;

    public ApplicationContextAwareProcessor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof ApplicationContextAware){
            ((ApplicationContextAware) bean).setApplicationContext(applicationContext);
        }
        // ioc1-7新增: 发布者感知接口
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(applicationContext);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
